﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Com.FastSearch.SharePoint.BL.SearchManager;
using Com.FastSearch.SharePoint.Interfaces;
using Com.FastSearch.Utils;
using Microsoft.SharePoint;

namespace Com.FastSearch.SharePoint.WebControls.ESPSearchWebParts.UI.Editors
{
    internal class ESPSearchConfigEditorPart : EditorPart
    {
        #region Constants

        public const string DEFAULT_URL_QUERY_PARAMETER = "k";
        public const string URL_QUERY_PARAMETER_LABEL = "URL Query Parameter";

        public const string DEFAULT_SEARCH_VIEW = "espsystemwebcluster";
        // View used of the viewlist could not be retrieved from the server

        public const string SEARCH_VIEW_LABEL_TEXT = "Search View ";
        public const string SEARCH_VIEW_HEADER_TEXT = "Search View ";

        public const string SEARCH_VIEW_TOOLTIP_TEXT =
            "Search against a particular view. 'espsystemwebcluster' searches all content!";

        public const string RESULT_CONTROLS_HEADER = "Result Controls";

        public const string NUMBER_OF_DOC_PER_PAGE_LABEL_TEXT = "Results per Page ";
        public const string NUMBER_OF_DOC_PER_PAGE_TOOLTIP_TEXT = "Number of documents shown per page.";

        public const string LINGUISTIC_HEADER = "Linguistics";
        public const string SYNONYM_LABEL_TEXT = "Synonyms";
        public const string SYNONYM_TOOLTIP_TEXT = "Enable/Disable Synonyms";

        public const string LEMMATIZATION_LABEL_TEXT = "Lemmatization ";
        public const string LEMMATIZATION_TOOLTIP_TEXT = "Enable/Disable Lemmatization";

        // Configure in spellchecking/suggestion web part???
        public const string SPELLCHECK_OFF_TEXT = "Off";
        public const string SPELLCHECK_SUGGEST_TEXT = "Suggest corrections";
        public const string SPELLCHECK_AUTO_TEXT = "Apply corrections automatically";

        public const string SPELLCHECK_LABEL_TEXT = "Spellchecking";
        public const string SPELLCHECK_TOOLTIP_TEXT = "Choose type of suggestion which shall be used";

        public const string ADDITIONAL_SEARCH_PARAMS_LABEL_TEXT = "Static Search Parameter:";

        public const string ADDITIONAL_SEARCH_PARAMS_TOOLTIP_TEXT =
            "Add static search parameter which are not explicitely exposed in any ESP Search WebPart to the query. Seperate with a ;. Example a=b;c=d.";

        public const string RESULT_SORTING_LABEL_TEXT = "Result Sorting ";

        public const string RESULT_SORTING_TOOLTIP_TEXT =
            "Sort the search results in a particular order. One rank profile + multiple sortable fields can be selected";


        public const string QUERY_TEMPLATE_SIMPLEALL =
            "content:string(\"{0}\", mode=\"SIMPLEALL\", annotation_class=\"{1}\")";

        public const string QUERY_TEMPLATE_SIMPLEANY =
            "content:string(\"{0}\", mode=\"SIMPLEANY\", annotation_class=\"{1}\")";

        public const string QUERY_TEMPLATE_PHRASE = "content:string(\"{0}\", mode=\"PHRASE\", annotation_class=\"{1}\")";


        public const string QUERY_TEMPLATE_HEADER = "Query Template used for searching";

        public const string QUERY_TEMPLATE_HEADER_TOOLTIP = "Specify the query template used for the search. " +
                                                            "Example: " + QUERY_TEMPLATE_PHRASE + "<br>" +
                                                            "Where {0} is replaces with the query and {1} with the annotation class 'user'";

        public const string QUERY_TEMPLATE_LABEL = "Defaults";
        public const string QUERY_TEMPLATE_LABEL_SIMPLEALL = "All Words";
        public const string QUERY_TEMPLATE_LABEL_SIMPLEANY = "Any Word";
        public const string QUERY_TEMPLATE_LABEL_PHRASE = "Exact Phrase";

        public const string QUERY_TEMPLATE_CUSTOM = "Custom  ";

        public const string STATIC_QUERY_PROPERTIES_HEADER = "Static Query Properties";

        public const string STATIC_QUERY_PROPERTIES_HEADER_TOOLTIP =
            "Static Query properties added to the search. Add as url encoded url properties, with & as parameter seperator. \nExample: a=b&c=d\n" +
            "NOTE: If parameters defined here are the same as the ones choosen above the ones defined here will be used!";

        public const string DEFAULT_QUERY_HEADER_TOOLTIP = "Default query string used if no value is specified";
        public const string DEFAULT_QUERY_HEADER = "Default Query String";


        public const string ESP_CONNECTION_HEADER = "ESP Connection String";

        #endregion

        #region Class variables

        private string _ErrorMessageConvert = null;
        private string _ErrorMessageView = null;
        private string _ErrorMessageSortview = null;

        private DropDownList _viewList;       

        private DropDownList _sortField;
        private DropDownList _sortDirection;
        private Dictionary<String, ISortField> _sortingFieldDict;

        private TextBox _resPerPage;
        private CheckBox _synonyms;
        private CheckBox _lemmatization;
        private RadioButtonList _spellcheckingList;

        private DropDownList _defaultQueryTemplates;
        private TextBox _customQueryTemplate;
        private RadioButton _radioDefaultQueryTemplate;
        private RadioButton _radioCustomQueryTemplate;
        private TextBox _staticQueryProperties;
        private TextBox _urlQueryParameter;
        private TextBox _defaultQuery;

        //ESP Connection
        private RadioButton _radioDefaultESPConnection;
        private RadioButton _radioCustomESPConnection;
        private TextBox _customESPConnection;


        Table editTable = new Table();

        #endregion

        public ESPSearchConfigEditorPart(string cat)
        {
        }

        public override bool ApplyChanges()
        {
            ESPSearchConfig espConf = WebPartToEdit as ESPSearchConfig;
            if (espConf != null)
            {
                EnsureChildControls();
                espConf.SearchView = _viewList.SelectedValue;
                espConf.SynonymFeature = _synonyms.Checked;
                espConf.LemmatizationFeature = _lemmatization.Checked;
                espConf.SpellcheckFeature = _spellcheckingList.SelectedValue;

                // Default to sorteable field.If rankprofile do not use the sort direction + or - in front....                
                espConf.ResultSorting = _sortDirection.SelectedValue + _sortField.SelectedValue;
                // Get all sort fields
                
                List<ISortField>  availableSorting = GetSortFields();
                
                foreach (ISortField o in availableSorting)
                {                    
                   _sortingFieldDict.Add(o.FieldName, o);
                }

                if (_sortingFieldDict.ContainsKey(_sortField.SelectedValue))
                {
                    ISortField field = _sortingFieldDict[_sortField.SelectedValue];
                    if (field.IsRankField)  {
                        espConf.ResultSorting = _sortField.SelectedValue;
                    }
                }                               
                
                espConf.StaticQueryProperties = _staticQueryProperties.Text;
                
                if (string.IsNullOrEmpty(_urlQueryParameter.Text))
                {
                    _urlQueryParameter.Text = DEFAULT_URL_QUERY_PARAMETER;
                }
                espConf.URLQueryParameter = _urlQueryParameter.Text;
                
                ApplyQueryTemplateChanges(espConf);
                ApplyESPConnectionChanges(espConf);

                try
                {
                    espConf.NumberOfResults = Convert.ToInt32(_resPerPage.Text);
                }
                catch
                {
                    _ErrorMessageConvert = "Could not convert entry '" + _resPerPage.Text + "' to integer!";
                    _resPerPage.Text = Convert.ToString(espConf.NumberOfResults);
                    return false;
                }

                espConf.DefaultQuery = _defaultQuery.Text;

                // Call a configure changed so the properties are written into the searchStore and take effect.
                espConf.ConfigurationChanged();
            }

            return (espConf != null);
        }

        private void ApplyESPConnectionChanges(ESPSearchConfig espConf)
        {
            if (_radioCustomESPConnection.Checked)
            {
                if (!string.IsNullOrEmpty(_customESPConnection.Text))
                {
                    espConf.ESPConnection = _customESPConnection.Text;
                } else // Fallback to site wide config
                {
                    espConf.ESPConnection = null;                 
                }
            } else
            {
                espConf.ESPConnection = null; ;      
            }
        }

        private void ApplyQueryTemplateChanges(ESPSearchConfig espConf)
        {
            if (! _radioDefaultQueryTemplate.Checked)
            {
                if (!string.IsNullOrEmpty(_customQueryTemplate.Text))
                {
                    espConf.QueryTemplate = _customQueryTemplate.Text;
                }
                else
                {
                    // Fallback to simple all
                    espConf.QueryTemplate = QUERY_TEMPLATE_SIMPLEALL;
                }
            }
            else
            {
                switch (_defaultQueryTemplates.SelectedValue)
                {
                    case QUERY_TEMPLATE_LABEL_PHRASE:
                        espConf.QueryTemplate = QUERY_TEMPLATE_PHRASE;
                        break;
                    case QUERY_TEMPLATE_LABEL_SIMPLEALL:
                        espConf.QueryTemplate = QUERY_TEMPLATE_SIMPLEALL;
                        break;
                    case QUERY_TEMPLATE_LABEL_SIMPLEANY:
                        espConf.QueryTemplate = QUERY_TEMPLATE_SIMPLEANY;
                        break;
                    default:
                        espConf.QueryTemplate = QUERY_TEMPLATE_SIMPLEANY;
                        break;
                }
            }
        }

        public override void SyncChanges()
        {
            ESPSearchConfig espConf = WebPartToEdit as ESPSearchConfig;
            if (espConf != null)
            {
                EnsureChildControls();                
                _resPerPage.Text = Convert.ToString(espConf.NumberOfResults);
                _synonyms.Checked = espConf.SynonymFeature;
                _lemmatization.Checked = espConf.LemmatizationFeature;
                _staticQueryProperties.Text = espConf.StaticQueryProperties;                
                _urlQueryParameter.Text = espConf.URLQueryParameter;
                _defaultQuery.Text = espConf.DefaultQuery;

                if (String.IsNullOrEmpty(espConf.ESPConnection))
                {
                    _customESPConnection.Text = "";
                    _radioDefaultESPConnection.Checked = true;
                } else
                {
                    _customESPConnection.Text = espConf.ESPConnection;
                    _radioCustomESPConnection.Checked = true;
                }

                SyncDropdownData(espConf);                

                SyncQueryTemplateChanges(espConf);
                try
                {
                    if (espConf.SpellcheckFeature != null)
                    {
                        _spellcheckingList.SelectedValue = espConf.SpellcheckFeature;
                    }
                    else
                    {
                        espConf.SpellcheckFeature = SpellCheckEnum.OFF.ToString();
                        _spellcheckingList.SelectedValue = espConf.SpellcheckFeature;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    _spellcheckingList.SelectedValue = SpellCheckEnum.OFF.ToString();
                }
            }
        }

        private void SyncQueryTemplateChanges(ESPSearchConfig espConf)
        {
            switch (espConf.QueryTemplate)
            {
                case QUERY_TEMPLATE_SIMPLEANY:
                case QUERY_TEMPLATE_SIMPLEALL:
                case QUERY_TEMPLATE_PHRASE:
                    {
                        _radioDefaultQueryTemplate.Checked = true;
                        _defaultQueryTemplates.SelectedValue = espConf.QueryTemplate;
                        break;
                    }
                default:
                    {
                        _radioCustomQueryTemplate.Checked = true;
                        _customQueryTemplate.Text = espConf.QueryTemplate;
                        break;
                    }
            }
        }

        /// <summary>
        /// Return a string array containing the sort direction in pos 0 and the field name in pos 1
        /// NOTE: For now only one single sorting is implemented.
        /// TODO: Implement multiple sorting.....
        /// </summary>
        /// <param name="sortString"></param>
        /// <returns></returns>
        private string[] GetSorting(string sortString)
        {
            if (sortString == null)
            {
                return new string[] {"+", "default"};
            }

            sortString = sortString.Trim();
            if ((sortString[0].Equals("+")) || (sortString[0].Equals("-")))
            {
                return new string[] {sortString.Substring(0, 1), sortString.Substring(1, sortString.Length)};
            }
            else
            {
                return new string[] {"+", sortString};
            }
        }
        private static void AddToEditSection(Table table1, Control editSection)
        {
            TableRow tr = new TableRow();
            TableCell tc = new TableCell();
            table1.Rows.Add(tr);
            tr.Cells.Add(tc);
            tc.Controls.Add(editSection);    
        }

        private void SyncDropdownData(ESPSearchConfig espConf)
        {
            try
            {
                // Fill views dropdown
                StringCollection availableViews = GetViews();
                _viewList.Items.Clear();
                foreach (string view in availableViews)
                {
                    _viewList.Items.Add(new ListItem(view, view));
                }
                _viewList.SelectedValue = espConf.SearchView;

                // Fill sorting dropdowns            
                List<ISortField> availableSorting = GetSortFields();

                _sortField.Items.Clear();
                
                foreach (ISortField o in availableSorting)
                {
                    _sortField.Items.Add(new ListItem(o.FieldName, o.FieldName));

                    if (_sortingFieldDict.ContainsKey(o.FieldName))
                    {
                        _sortingFieldDict.Remove(o.FieldName);
                    }
                    _sortingFieldDict.Add(o.FieldName, o);
                }

                if (!string.IsNullOrEmpty(espConf.ResultSorting))
                {
                    if (espConf.ResultSorting.StartsWith("-"))
                    {
                        _sortDirection.SelectedValue = "-";
                    }
                    else
                    {
                        _sortDirection.SelectedValue = "+";
                    }

                    if (espConf.ResultSorting.StartsWith("+") || espConf.ResultSorting.StartsWith("-"))
                    {
                        string field = espConf.ResultSorting.Substring(1);
                        _sortField.SelectedValue = espConf.ResultSorting.Substring(1);
                    }
                    else
                    {
                        _sortField.SelectedValue = espConf.ResultSorting;
                    }
                }
            }
            catch (Exception) { }
        } 

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
                        
            editTable = new Table();
            
            // ESP Connection
            Table table = new Table();
            CreateQRServerBody(table);            
            AddToEditSection(editTable, table);

            // Views
            table = new Table();
            CreateSearchViewBody(table);            
            AddToEditSection(editTable, table);

            // Results per page
            table = new Table();
            CreateResultControlPageBody(table);            
            AddToEditSection(editTable, table);

            // Linguistics
            table = new Table();
            CreateLinguisticsPageBody(table);            
            AddToEditSection(editTable, table);

            // Tamplate
            table = new Table();
            CreateQueryTemplatePageBody(table);            
            AddToEditSection(editTable, table);

            // Advanced Search Properties
            table = new Table();
            CreateAdvancedPropertiesPageBody(table);            
            AddToEditSection(editTable, table);

            Controls.Add(editTable);
            
        }

        // Some properties only show if it's not search group 0
        // Example is the query parameter.

        private bool IsSearchGroup0()
        {
            ESPSearchConfig espConf = WebPartToEdit as ESPSearchConfig;
            if (espConf != null)
            {
                return (espConf.ESPSearchGroupID == ESPSearchGroupEnum.Group0);
            }
            return false;
        }


        // Delegate to fill body
        public delegate void WriteUserSectionBodyDelegate(HtmlTextWriter writer);

        public void CreateQRServerBody(Table table)
        {

            _radioDefaultESPConnection = new RadioButton();
            _radioDefaultESPConnection.GroupName = "espconnectiongroup";
            _radioDefaultESPConnection.Checked = true;  // by default use the default site wide esp connection
            _radioCustomESPConnection = new RadioButton();
            _radioCustomESPConnection.GroupName = "espconnectiongroup";
            _customESPConnection = new TextBox();
            
            table.BorderStyle = BorderStyle.None;
            table.CellSpacing = 2;
            TableCell leftCell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftCell, null, ESP_CONNECTION_HEADER, null);
            leftCell.Controls.Add(new LiteralControl("QRServer Connection (Default uses the Connection configured in Web Application level!<br/>" +
                "To Change the default connection go to <a target=\"_ESPQRSERVERCONFIG\" href=\"/_layouts/ESPConnectionConfig/ESPConnectionConfig.aspx\" >\"Site Settings \" -> \"Site Collection Administration\" -> \"ESP Query Server Connections\"</a> or configure a custom connection per search group below"));

            leftCell = new TableCell();
            TableCell rightCell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftCell, rightCell, null, null);
            leftCell.Controls.Add(_radioDefaultESPConnection);
            rightCell.Controls.Add(new LiteralControl(GetDefaultQRServerConnection()));

            leftCell = new TableCell();
            rightCell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftCell, rightCell, null,null);
            leftCell.Controls.Add(_radioCustomESPConnection);
            rightCell.Controls.Add(_customESPConnection);            
        }

        private static void CreatedConfigTableRow(Table table, TableRow row, TableCell cell1, TableCell cell2, string label, string tooltip)        
        {
            if (!String.IsNullOrEmpty(label))
            {
                TableHeaderRow thr = new TableHeaderRow();
                thr.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Left;
                table.Rows.Add(thr);
                TableHeaderCell tc = new TableHeaderCell();
                tc.ColumnSpan = 2;
                tc.Controls.Add(CreateLabel(label, tooltip, "UserSectionHead"));
                thr.Cells.Add(tc);
                table.Rows.Add(thr);
            }

            table.Rows.Add(row);
            row.Cells.Add(cell1);
            if (cell2 == null)
            {
                cell1.ColumnSpan = 2;
            } else
            {
                row.Cells.Add(cell2);  
            }
        }
       
        public void CreateSearchViewBody(Table table)
        {
            // Get the available views
            _viewList = new DropDownList();
            Controls.Add(_viewList);            

            // Create the output
            TableCell leftcell = new TableCell();
            TableCell rightcell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftcell, rightcell, SEARCH_VIEW_HEADER_TEXT, null);            
            leftcell.Controls.Add(CreateLabel(SEARCH_VIEW_LABEL_TEXT, SEARCH_VIEW_TOOLTIP_TEXT));
            rightcell.Controls.Add(_viewList);
            
            if (_ErrorMessageView != null)
            {
                AddErrorMessage(table, _ErrorMessageView);
            }            
        }

        public void CreateResultControlPageBody(Table table)
        {            
            _resPerPage = new TextBox();

            TableCell leftcell = new TableCell();
            TableCell rightcell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftcell, rightcell, RESULT_CONTROLS_HEADER, RESULT_SORTING_TOOLTIP_TEXT);
            leftcell.Controls.Add(CreateLabel(NUMBER_OF_DOC_PER_PAGE_LABEL_TEXT, NUMBER_OF_DOC_PER_PAGE_TOOLTIP_TEXT));
            rightcell.Controls.Add(_resPerPage);
            
            if (_ErrorMessageConvert != null)
            {
                AddErrorMessage(table, _ErrorMessageConvert);
            }


            _sortField = new DropDownList();
            _sortingFieldDict = new Dictionary<string, ISortField>();
            Controls.Add(_sortField);
            _sortDirection = new DropDownList();
            Controls.Add(_sortDirection);
            _sortDirection.Items.Add(new ListItem("Ascending", "+"));
            _sortDirection.Items.Add(new ListItem("Descending", "-"));

            leftcell = new TableCell();
            rightcell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftcell, rightcell, null, null);
            leftcell.Controls.Add(CreateLabel(RESULT_SORTING_LABEL_TEXT, RESULT_SORTING_TOOLTIP_TEXT));
            rightcell.Controls.Add(_sortField);
            rightcell.Controls.Add(_sortDirection);
                                                
            if (_ErrorMessageSortview != null)
            {
                AddErrorMessage(table, _ErrorMessageSortview);
            }
        }

        public void CreateLinguisticsPageBody(Table table)
        {

            // synonyms
            _synonyms = new CheckBox();
            _synonyms.Text = SYNONYM_LABEL_TEXT;
            _synonyms.ToolTip = SYNONYM_TOOLTIP_TEXT;            

            // Lemmatization
            _lemmatization = new CheckBox();
            _lemmatization.Text = LEMMATIZATION_LABEL_TEXT;
            _lemmatization.ToolTip = LEMMATIZATION_TOOLTIP_TEXT;            

            // Spellchecking
            _spellcheckingList = new RadioButtonList();
            _spellcheckingList.Items.Add(
                new ListItem(SPELLCHECK_OFF_TEXT, SpellCheckEnum.OFF.ToString()));
            _spellcheckingList.Items.Add(
                new ListItem(SPELLCHECK_SUGGEST_TEXT, SpellCheckEnum.SUGGEST.ToString()));
            _spellcheckingList.Items.Add(
                new ListItem(SPELLCHECK_AUTO_TEXT, SpellCheckEnum.ON.ToString()));                        

            TableCell leftcell = new TableCell();
            TableCell rightcell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftcell, rightcell, LINGUISTIC_HEADER, null);
            leftcell.Controls.Add(_synonyms);
            rightcell.Controls.Add(_lemmatization);


            leftcell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftcell, null, null, null);
            leftcell.Controls.Add(CreateLabel(SPELLCHECK_SUGGEST_TEXT, SPELLCHECK_TOOLTIP_TEXT));

            leftcell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftcell, null, null, null);
            leftcell.Controls.Add(_spellcheckingList);            
        }


        public void CreateAdvancedPropertiesPageBody(Table table)
        {

            TableCell leftcell = new TableCell();
            TableCell rightCell = new TableCell();
            _staticQueryProperties = new TextBox();            
            _urlQueryParameter = new TextBox();
            _defaultQuery = new TextBox();
            
            CreatedConfigTableRow(table, new TableRow(), leftcell, rightCell, STATIC_QUERY_PROPERTIES_HEADER, STATIC_QUERY_PROPERTIES_HEADER_TOOLTIP);
            leftcell.Controls.Add(_staticQueryProperties);

            leftcell = new TableCell();
            rightCell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftcell, rightCell, DEFAULT_QUERY_HEADER, DEFAULT_QUERY_HEADER_TOOLTIP);
            leftcell.Controls.Add(_defaultQuery);

            if (!IsSearchGroup0())
            {
                leftcell = new TableCell();
                rightCell = new TableCell();
                CreatedConfigTableRow(table, new TableRow(), leftcell, rightCell, URL_QUERY_PARAMETER_LABEL, "");
                leftcell.Controls.Add(_urlQueryParameter);                
            }            
        }

        public void CreateQueryTemplatePageBody(Table table)
        {

            _radioDefaultQueryTemplate = new RadioButton();
            _radioDefaultQueryTemplate.GroupName = "templateRadioSelection";            
            _radioDefaultQueryTemplate.Checked = true;            
            _radioCustomQueryTemplate = new RadioButton();            
            _radioCustomQueryTemplate.GroupName = "templateRadioSelection";           
            _defaultQueryTemplates = new DropDownList();
            _defaultQueryTemplates.Items.Add(
                new ListItem(QUERY_TEMPLATE_LABEL_SIMPLEANY, QUERY_TEMPLATE_LABEL_SIMPLEANY));            
            _defaultQueryTemplates.Items.Add(
                new ListItem(QUERY_TEMPLATE_LABEL_SIMPLEALL, QUERY_TEMPLATE_LABEL_SIMPLEALL));
            _defaultQueryTemplates.Items.Add(new ListItem(QUERY_TEMPLATE_LABEL_PHRASE, QUERY_TEMPLATE_LABEL_PHRASE));                        
            _customQueryTemplate = new TextBox();                        

            TableCell leftCell = new TableCell();
            TableCell rightCell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftCell, rightCell, QUERY_TEMPLATE_HEADER, QUERY_TEMPLATE_HEADER_TOOLTIP);            
            leftCell.Controls.Add(_radioDefaultQueryTemplate);
            rightCell.Controls.Add(_defaultQueryTemplates);


            leftCell = new TableCell();
            rightCell = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), leftCell, rightCell, null, null);
            leftCell.Controls.Add(_radioCustomQueryTemplate);
            rightCell.Controls.Add(_customQueryTemplate);
        }
                    
        protected static Label CreateLabel(string labelText, string toolTip)
        {
            return CreateLabel(labelText, toolTip, null);
            
        }

        protected static Label CreateLabel(string labelText, string toolTip, string cssClass)
        {
            Label lb = new Label();
            lb.Text = labelText;
            if (!String.IsNullOrEmpty(cssClass) )
            {
                lb.CssClass = cssClass;
            }
            if (toolTip != null)
            {
                lb.ToolTip = toolTip;
            }
            return lb;
        }

        protected static void AddLabel(WebControl parent, string labelText, string toolTip)
        {            
            parent.Controls.Add(CreateLabel(labelText, toolTip));            
        }

        private void AddErrorMessage(Table table, string message)
        {            
            Label errorMessage = new Label();
            errorMessage.Text = message;
            errorMessage.ApplyStyle(Zone.ErrorStyle);
            TableCell cell1 = new TableCell();
            CreatedConfigTableRow(table, new TableRow(), cell1, null, null, null);
            cell1.Controls.Add(errorMessage);                        
        }

        private string GetDefaultQRServerConnection()
        {
            //IESPSearchManager manager = GetSearchManagerFactory().Create(SPContext.Current.Site.WebApplication);
            //return manager.SPWebApplicationQRServersConfig;
            return ESPSearchManager.GetSPWebApplicationQRServerconfig(SPContext.Current.Site.WebApplication);

        }

        private IESPSearchManagerFactory GetSearchManagerFactory()
        {
            return SimpleFactoryManager<IESPSearchManagerFactory>.Factory;
        }

        private IESPSearchManager GetSearchManager()
        {
            IESPSearchManagerFactory fact = GetSearchManagerFactory();
            // If a custom esp connection shall be used            
            ESPSearchConfig espConf = WebPartToEdit as ESPSearchConfig;           
            if (_radioCustomESPConnection != null && _radioCustomESPConnection.Checked)
            {
                return fact.Create(_customESPConnection.Text);
            }
            /*if (espConf != null && espConf.ESPConnection != null)
            {
                return fact.Create(espConf.ESPConnection);                
            }*/
            return fact.Create(SPContext.Current.Site.WebApplication);
        }

        /// <summary>
        /// Return available views.
        /// </summary>
        /// <returns>string array of views. If none are available or an error occures an ampty array is returned. Never null</returns>
        private StringCollection GetViews()
        {
            try
            {
                IESPSearchManager sm = GetSearchManager();
                return sm.GetSearchViews();
            }
            catch (Exception)
            {
                _ErrorMessageView = "Views could not be retrieved from ESP Search!";
            }
            return new StringCollection();
        }

        private List<ISortField> GetSortFields()
        {
            try
            {
                IESPSearchManager sm = GetSearchManager();
                return sm.GetSortableFieldsAndRankProfiles(_viewList.SelectedValue);
            }
            catch (Exception)
            {
                _ErrorMessageSortview = "Sorting Fields could not be retrieved from ESP Search!";
            }
            return new List<ISortField>();
        }
    }
}